from django.db import models
import os
from settings import MEDIA_ROOT, MEDIA_URL, STATIC_URL
from lads.image import init_thumbnail, init_small_thumbnail, Thumbnail

class ThumbnailModel( models.Model ):
	def __init__( self, *args, **kwargs ):
		super( ThumbnailModel, self ).__init__( *args, **kwargs )
		self._old_image = self.image

	@staticmethod
	def generate_path( instance, item, prefix ):
		from dargent.utils import while_path_exists
		path = "{0}{1}.jpg".format( prefix, item )
		full_path = os.path.join( MEDIA_ROOT, path )
		filename = while_path_exists( full_path )
		new_path = "{0}".format( prefix ) + filename
		setattr( instance, '_image_path', new_path )
		return new_path
	
	def save( self, *args, **kwargs ):
		result = super( ThumbnailModel, self ).save( *args, **kwargs )
		if self._old_image:
			if self.image != self._old_image:
				image_name = self._image_path
				item = self.__class__.objects.get( id = self.pk )
				thumbnail = init_thumbnail( image_name )
				item.thumbnail = thumbnail
				self.thumbnail = thumbnail
				if hasattr( self, '_init_small_thumbnail' ):
					if self._init_small_thumbnail:
						init_small_thumbnail( image_name )
				item.save()
		return result

	def has_thumbnail( self ):
		return self.thumbnail != None

	def get_thumbnail_url( self ):
		if self.thumbnail != None:
			result = MEDIA_URL + self.thumbnail.name
		else:
			result = STATIC_URL + 'img/icon.jpg'

		return result

	thumbnail_url = property( get_thumbnail_url )
	
	class Meta:
		abstract = True